<template>
  <div class="special-training-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">专项训练</h1>
      <div class="header-actions">
        <el-button @click="refreshTrainingList">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button @click="viewTrainingHistory">
          <el-icon><History /></el-icon>
          训练历史
        </el-button>
      </div>
    </div>

    <!-- 训练分类导航 -->
    <div class="category-navigation">
      <el-card class="category-card">
        <div class="category-content">
          <div class="category-tabs">
            <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
              <el-tab-pane label="全部训练" name="all" />
              <el-tab-pane label="图形推理" name="graphics" />
              <el-tab-pane label="定义判断" name="definition" />
              <el-tab-pane label="类比推理" name="analogy" />
              <el-tab-pane label="逻辑判断" name="logic" />
              <el-tab-pane label="言语理解" name="language" />
              <el-tab-pane label="数量关系" name="quantity" />
              <el-tab-pane label="资料分析" name="data" />
            </el-tabs>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 推荐训练 -->
    <div v-if="activeTab === 'all'" class="recommended-section">
      <h2 class="section-title">
        <el-icon><Star /></el-icon>
        推荐训练
      </h2>
      <div class="recommended-grid">
        <el-card
          v-for="training in recommendedTrainings"
          :key="training.id"
          class="recommended-card"
          hoverable
          @click="startTraining(training.id)"
        >
          <div class="recommended-card-content">
            <div class="recommended-card-header">
                <div class="recommended-card-title">{{ training.title }}</div>
              <div class="recommended-card-badge" :class="`badge-${training.difficulty}`">
                {{ getDifficultyName(training.difficulty) }}
              </div>
            </div>
            <div class="recommended-card-info">
              <div class="recommended-card-meta">
                <span class="meta-item">
                  <el-icon><Reading /></el-icon>
                  {{ training.questionCount }}题
                </span>
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  {{ training.estimatedTime }}分钟
                </span>
                <span class="meta-item">
                  <el-icon><LineChart /></el-icon>
                  {{ training.passRate }}%通过率
                </span>
              </div>
              <div class="recommended-card-desc">{{ training.description }}</div>
            </div>
            <div class="recommended-card-footer">
              <span class="recommended-card-category">{{ training.categoryName }}</span>
              <el-button type="primary" size="small">开始训练</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 训练列表 -->
    <div class="trainings-list-section">
      <div class="trainings-header">
        <h2 class="section-title">训练列表</h2>
        <div class="trainings-filter">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索训练名称"
            prefix-icon="Search"
            class="search-input"
            @keyup.enter="applyFilters"
          />
          <el-select v-model="difficultyFilter" placeholder="难度" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
          <el-select v-model="sortBy" placeholder="排序" class="filter-select">
            <el-option label="默认" value="default" />
            <el-option label="最新" value="newest" />
            <el-option label="题目数(从多到少)" value="questionsDesc" />
            <el-option label="题目数(从少到多)" value="questionsAsc" />
            <el-option label="通过率(从高到低)" value="passRateDesc" />
            <el-option label="通过率(从低到高)" value="passRateAsc" />
          </el-select>
          <el-button type="primary" @click="applyFilters">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
        </div>
      </div>
      
      <el-card class="trainings-card">
        <div class="trainings-content">
          <div v-if="filteredTrainings.length === 0" class="no-trainings">
            <el-empty description="暂无训练" />
            <div class="no-trainings-text">当前分类下暂无专项训练</div>
          </div>
          
          <el-table
            v-else
            v-loading="isLoading"
            :data="paginatedTrainings"
            style="width: 100%"
            border
            row-key="id"
            highlight-current-row
          >
            <el-table-column prop="id" label="ID" width="80" align="center" />
            
            <el-table-column prop="title" label="训练名称" min-width="200">
              <template #default="scope">
                <div class="training-title">
                  <span class="title-text">{{ scope.row.title }}</span>
                  <el-tag 
                    v-if="scope.row.isNew" 
                    type="danger" 
                    size="small"
                    class="new-tag"
                  >
                    新
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="categoryName" label="分类" width="120" align="center">
              <template #default="scope">
                <el-tag>{{ scope.row.categoryName }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="difficulty" label="难度" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getDifficultyType(scope.row.difficulty)">{{ getDifficultyName(scope.row.difficulty) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="questionCount" label="题目数量" width="100" align="center" />
            
            <el-table-column prop="estimatedTime" label="预计时间(分钟)" width="120" align="center" />
            
            <el-table-column prop="passRate" label="通过率(%)" width="100" align="center">
              <template #default="scope">
                <el-progress :percentage="scope.row.passRate" :format="formatPassRate" :show-text="false" width="80" />
                <span class="pass-rate-text">{{ scope.row.passRate }}%</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="lastUpdateDate" label="更新时间" width="160" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.lastUpdateDate) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getTrainingStatusType(scope.row.status)">{{ getTrainingStatusName(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="startTraining(scope.row.id)"
                >
                  <el-icon><Play /></el-icon>
                  开始训练
                </el-button>
                <el-button
                  size="small"
                  @click="viewTrainingDetails(scope.row.id)"
                >
                  <el-icon><Reading /></el-icon>
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div v-if="filteredTrainings.length > 0" class="trainings-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredTrainings.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 训练详情对话框 -->
    <el-dialog
      v-model="trainingDetailDialogVisible"
      title="训练详情"
      width="800px"
    >
      <div v-if="selectedTrainingDetail" class="training-detail-content">
        <div class="training-detail-header">
          <h3 class="training-detail-title">{{ selectedTrainingDetail.title }}</h3>
          <div class="training-detail-badges">
            <el-tag :type="getDifficultyType(selectedTrainingDetail.difficulty)">
              {{ getDifficultyName(selectedTrainingDetail.difficulty) }}
            </el-tag>
            <el-tag type="info">{{ selectedTrainingDetail.categoryName }}</el-tag>
            <el-tag v-if="selectedTrainingDetail.isNew" type="danger">新</el-tag>
          </div>
        </div>
        
        <div class="training-detail-stats">
          <div class="stat-item">
            <span class="stat-label">题目数量：</span>
            <span class="stat-value">{{ selectedTrainingDetail.questionCount }}题</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">预计时间：</span>
            <span class="stat-value">{{ selectedTrainingDetail.estimatedTime }}分钟</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">通过率：</span>
            <span class="stat-value">{{ selectedTrainingDetail.passRate }}%</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已训练人数：</span>
            <span class="stat-value">{{ selectedTrainingDetail.trainingCount }}人</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">更新时间：</span>
            <span class="stat-value">{{ formatDate(selectedTrainingDetail.lastUpdateDate) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">状态：</span>
            <span class="stat-value">{{ getTrainingStatusName(selectedTrainingDetail.status) }}</span>
          </div>
        </div>
        
        <div class="training-detail-description">
          <h4>训练说明</h4>
          <p>{{ selectedTrainingDetail.description }}</p>
        </div>
        
        <div class="training-detail-knowledge">
          <h4>覆盖知识点</h4>
          <div class="knowledge-tags">
            <el-tag v-for="tag in selectedTrainingDetail.knowledgePoints" :key="tag" class="knowledge-tag">
              {{ tag }}
            </el-tag>
          </div>
        </div>
        
        <div class="training-detail-structure">
          <h4>训练结构</h4>
          <el-table
            :data="selectedTrainingDetail.structure"
            style="width: 100%"
            border
            size="small"
          >
            <el-table-column prop="type" label="题型" width="100" align="center" />
            <el-table-column prop="count" label="数量" width="80" align="center" />
            <el-table-column prop="description" label="说明" />
          </el-table>
        </div>
        
        <div v-if="selectedTrainingDetail.myProgress" class="training-detail-progress">
          <h4>我的训练进度</h4>
          <div class="progress-info">
            <el-progress :percentage="selectedTrainingDetail.myProgress.completionRate" />
            <div class="progress-stats">
              <span>已完成：{{ selectedTrainingDetail.myProgress.completedCount }}题</span>
              <span>正确率：{{ selectedTrainingDetail.myProgress.accuracyRate }}%</span>
              <span v-if="selectedTrainingDetail.myProgress.lastTrainingDate">上次训练：{{ formatDate(selectedTrainingDetail.myProgress.lastTrainingDate) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="training-detail-footer">
          <el-button @click="trainingDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="selectedTrainingDetail?.id && startTraining(selectedTrainingDetail.id)">
            <el-icon><Play /></el-icon>
            立即训练
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 训练开始确认对话框 -->
    <el-dialog
      v-model="startTrainingDialogVisible"
      title="开始训练"
      width="600px"
    >
      <div v-if="selectedTrainingDetail" class="start-training-content">
        <div class="start-training-header">
          <h3>{{ selectedTrainingDetail.title }}</h3>
          <p class="start-training-desc">{{ selectedTrainingDetail.description }}</p>
        </div>
        
        <div class="start-training-notice">
          <div class="notice-item">
            <el-icon><InfoFilled /></el-icon>
            <span>本次训练共 {{ selectedTrainingDetail.questionCount }} 道题，预计用时 {{ selectedTrainingDetail.estimatedTime }} 分钟</span>
          </div>
          <div class="notice-item">
            <el-icon><InfoFilled /></el-icon>
            <span>请确保网络稳定，避免中途退出影响训练效果</span>
          </div>
          <div class="notice-item">
            <el-icon><InfoFilled /></el-icon>
            <span>完成训练后可以查看详细的答题分析和解析</span>
          </div>
        </div>
        
        <div class="start-training-options">
          <el-checkbox v-model="trainingOptions.timerEnabled" class="option-item">
            <el-icon><Clock /></el-icon>
            启用计时器
          </el-checkbox>
          <el-checkbox v-model="trainingOptions.randomOrder" class="option-item">
            <el-icon><Shuffle /></el-icon>
            随机出题顺序
          </el-checkbox>
          <el-checkbox v-model="trainingOptions.showExplanation" class="option-item">
            <el-icon><Reading /></el-icon>
            答题后立即显示解析
          </el-checkbox>
        </div>
      </div>
      
      <template #footer>
        <span class="start-training-footer">
          <el-button @click="startTrainingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStartTraining" :loading="isStartingTraining">
            <el-icon><Play /></el-icon>
            确认开始
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 训练进行中对话框 -->
    <el-dialog
      v-model="trainingInProgressDialogVisible"
      title="训练进行中"
      width="900px"
      :fullscreen="isTrainingFullscreen"
      :before-close="handleTrainingDialogClose"
    >
      <!-- 训练进度 -->
      <div class="training-progress">
        <div class="progress-header">
          <h3>{{ currentTraining?.title }}</h3>
          <div class="progress-stats">
            <span class="progress-count">{{ currentQuestionIndex + 1 }}/{{ currentTraining?.questionCount }} 题</span>
            <span v-if="trainingTimer > 0" class="progress-time">用时: {{ formatTime(trainingTimer) }}</span>
            <span v-if="trainingOptions.timerEnabled" class="progress-remaining" :class="{ 'time-warning': remainingTime < 60, 'time-danger': remainingTime < 30 }">
              剩余: {{ formatTime(remainingTime) }}
            </span>
          </div>
        </div>
        <el-progress
          :percentage="(currentQuestionIndex + 1) / (currentTraining?.questionCount || 1) * 100"
          :format="formatTrainingProgress"
        />
        
        <!-- 题目导航 -->
        <div v-if="currentTraining" class="question-navigation">
          <div class="navigation-label">题目导航：</div>
          <div class="navigation-items">
            <div
              v-for="(question, index) in currentTraining.questions"
              :key="index"
              :class="[
                'navigation-item',
                { 
                  'current': index === currentQuestionIndex, 
                  'completed': question.isCompleted,
                  'marked': question.isMarked
                }
              ]"
              @click="jumpToQuestion(index)"
              :title="`第 ${index + 1} 题`"
            >
              {{ index + 1 }}
              <div v-if="question.isMarked" class="marked-indicator">
                <el-icon><Star /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 题目内容 -->
      <div v-if="currentQuestion" class="question-content">
        <div class="question-header">
          <span class="question-type">{{ getQuestionTypeName(currentQuestion.type) }}</span>
          <span class="question-difficulty" :class="`difficulty-${currentQuestion.difficulty}`">
            {{ getDifficultyName(currentQuestion.difficulty) }}
          </span>
          <el-button
            size="small"
            :icon="currentQuestion.isMarked ? 'StarFilled' : 'Star'"
            :class="{ 'marked-button': currentQuestion.isMarked }"
            @click="toggleMarkQuestion"
            title="标记题目"
          />
        </div>
        
        <div class="question-stem">
          <h4>{{ currentQuestion.stem }}</h4>
          <div v-if="currentQuestion.imageUrl" class="question-image">
            <img :src="currentQuestion.imageUrl" :alt="currentQuestion.stem" />
          </div>
        </div>
        
        <!-- 选项 -->
        <div v-if="currentQuestion.options" class="question-options">
          <div
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            :class="['option-item', { 
              'selected': currentQuestion.selectedOptions.includes(index), 
              'disabled': currentQuestion.isCompleted 
            }]"
            @click="selectOption(index)"
          >
            <div class="option-label">{{ getOptionLabel(index) }}</div>
            <div class="option-content">{{ option }}</div>
          </div>
        </div>
        
        <!-- 填空/简答 -->
        <div v-else-if="currentQuestion.type === 'blank' || currentQuestion.type === 'essay'" class="question-answer-input">
          <el-input
            v-model="textAnswer"
            :type="currentQuestion.type === 'essay' ? 'textarea' : 'text'"
            placeholder="请输入答案"
            :autosize="currentQuestion.type === 'essay' ? { minRows: 4, maxRows: 8 } : false"
            :disabled="currentQuestion.isCompleted"
          />
        </div>
        
        <!-- 答案和解析 (答题后显示) -->
        <div v-if="currentQuestion.isCompleted && trainingOptions.showExplanation" class="answer-explanation">
          <div class="user-answer">
            <h4>您的答案:</h4>
            <p>{{ getUserAnswerDisplay() }}</p>
          </div>
          
          <div class="correct-answer">
            <h4>正确答案:</h4>
            <p>{{ getCorrectAnswerDisplay() }}</p>
          </div>
          
          <div class="explanation">
            <h4>解析:</h4>
            <p>{{ currentQuestion.explanation }}</p>
          </div>
        </div>
      </div>
      
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="training-dialog-footer">
          <el-button @click="toggleTrainingFullscreen">
            <el-icon>{{ isTrainingFullscreen ? 'MinusSquare' : 'PlusSquare' }}</el-icon>
            {{ isTrainingFullscreen ? '退出全屏' : '全屏' }}
          </el-button>
          <div class="training-navigation-buttons">
            <el-button
              @click="prevQuestion"
              :disabled="currentQuestionIndex === 0 || isSubmittingAnswer"
            >
              <el-icon><ArrowLeft /></el-icon>
              上一题
            </el-button>
            <el-button
              v-if="!currentQuestion?.isCompleted"
              type="primary"
              @click="submitAnswer"
              :loading="isSubmittingAnswer"
            >
              提交答案
            </el-button>
            <el-button
              v-else
              type="primary"
              @click="nextQuestion"
              :disabled="currentQuestionIndex === (currentTraining?.questions.length || 1) - 1 || isSubmittingAnswer"
            >
              下一题
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <el-button danger @click="handleTrainingDialogClose">
            <el-icon><Stop /></el-icon>
            结束训练
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 训练结果对话框 -->
    <el-dialog
      v-model="trainingResultDialogVisible"
      title="训练结果"
      width="900px"
      :before-close="handleResultDialogClose"
    >
      <!-- 训练结果概览 -->
      <div class="result-overview">
        <div class="result-header">
          <h3>{{ completedTraining?.title }}</h3>
          <div class="result-stats">
            <span>总用时: {{ formatTime(completedTraining?.totalTime || 0) }}</span>
            <span>完成时间: {{ formatDateTime(completedTraining?.completionDate || new Date()) }}</span>
          </div>
        </div>
        
        <!-- 结果统计卡片 -->
        <div class="result-stats-cards">
          <el-card class="result-card score-card">
            <div class="result-card-content">
              <div class="result-card-title">得分</div>
              <div class="result-card-value">{{ completedTraining?.score }}分</div>
              <div class="result-card-subtitle">总分: {{ completedTraining?.totalScore }}分</div>
            </div>
          </el-card>
          
          <el-card class="result-card accuracy-card">
            <div class="result-card-content">
              <div class="result-card-title">正确率</div>
              <div class="result-card-value">{{ completedTraining?.accuracyRate }}%</div>
              <div class="result-card-subtitle">{{ completedTraining?.correctCount }}/{{ completedTraining?.totalCount }}题</div>
            </div>
          </el-card>
          
          <el-card class="result-card difficulty-card">
            <div class="result-card-content">
              <div class="result-card-title">难度系数</div>
              <div class="result-card-value">{{ completedTraining?.difficultyLevel }}</div>
              <div class="result-card-subtitle">{{ getDifficultyName(completedTraining?.difficulty || 'medium') }}</div>
            </div>
          </el-card>
          
          <el-card class="result-card rank-card">
            <div class="result-card-content">
              <div class="result-card-title">排名</div>
              <div class="result-card-value">{{ completedTraining?.ranking }}%</div>
              <div class="result-card-subtitle">击败了 {{ completedTraining?.beatenPercentage }}% 的用户</div>
            </div>
          </el-card>
        </div>
      </div>
      
      <!-- 答题分析 -->
      <div class="answer-analysis">
        <h4>答题分析</h4>
        
        <!-- 题型正确率 -->
        <div class="analysis-section">
          <h5>题型正确率</h5>
          <div class="type-accuracy">
            <div v-for="item in completedTraining?.typeAccuracy" :key="item.type" class="type-accuracy-item">
              <span class="type-name">{{ getQuestionTypeName(item.type) }}</span>
              <el-progress :percentage="item.accuracy" :format="formatProgressPercentage" width="200" />
              <span class="type-stats">{{ item.correctCount }}/{{ item.totalCount }}题</span>
            </div>
          </div>
        </div>
        
        <!-- 知识点掌握情况 -->
        <div class="analysis-section">
          <h5>知识点掌握情况</h5>
          <div class="knowledge-mastery">
            <el-tag
              v-for="item in completedTraining?.knowledgeMastery"
              :key="item.point"
              :type="getMasteryType(item.masteryLevel)"
              class="mastery-tag"
              effect="dark"
            >
              {{ item.point }} ({{ item.masteryLevel }}%)
            </el-tag>
          </div>
        </div>
        
        <!-- 错题列表 -->
        <div class="analysis-section">
          <h5>错题列表</h5>
          <div v-if="completedTraining?.wrongQuestions.length === 0" class="no-wrong-questions">
            <el-empty description="暂无错题" />
            <div class="no-wrong-questions-text">恭喜您，本次训练全部答对！</div>
          </div>
          <div v-else class="wrong-questions-list">
            <div
              v-for="question in completedTraining?.wrongQuestions"
              :key="question.id"
              class="wrong-question-item"
            >
              <div class="wrong-question-header">
                <span class="wrong-question-index">第 {{ question.index + 1 }} 题</span>
                <el-button size="small" @click="reviewWrongQuestion(question.id)">
                  <el-icon><Reading /></el-icon>
                  查看详情
                </el-button>
              </div>
              <div class="wrong-question-stem">{{ question.stem }}</div>
            </div>
          </div>
        </div>
        
        <!-- 学习建议 -->
        <div class="analysis-section">
          <h5>学习建议</h5>
          <div class="learning-suggestions">
            <div v-for="suggestion in completedTraining?.learningSuggestions" :key="suggestion.id" class="suggestion-item">
              <el-icon><Lightbulb /></el-icon>
              <span>{{ suggestion.content }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="result-dialog-footer">
          <el-button @click="handleResultDialogClose">关闭</el-button>
          <el-button @click="saveTrainingResult">
            <el-icon><Save /></el-icon>
            保存结果
          </el-button>
          <el-button @click="shareTrainingResult">
            <el-icon><Share /></el-icon>
            分享成绩
          </el-button>
          <el-button type="primary" @click="reviewAllQuestions">
            <el-icon><Reading /></el-icon>
            查看全部题目
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
// import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// Element Plus图标已在main.ts中全局注册，不需要单独导入

// 路由
// const router = useRouter()
// const route = useRoute()

// 响应式数据
const isLoading = ref(false)
const activeTab = ref('all')
const searchKeyword = ref('')
const difficultyFilter = ref('all')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(10)
const trainingDetailDialogVisible = ref(false)
const startTrainingDialogVisible = ref(false)
const trainingInProgressDialogVisible = ref(false)
const trainingResultDialogVisible = ref(false)
const isTrainingFullscreen = ref(false)
const isStartingTraining = ref(false)
const isSubmittingAnswer = ref(false)
const trainingTimer = ref(0)
const timerInterval = ref<number | null>(null)
const currentQuestionIndex = ref(0)
const textAnswer = ref('')

// 训练选项
const trainingOptions = reactive({
  timerEnabled: true,
  randomOrder: false,
  showExplanation: true
})

// 专项训练接口
interface Training {
  id: string
  title: string
  description: string
  categoryId: string
  categoryName: string
  difficulty: 'easy' | 'medium' | 'hard'
  questionCount: number
  estimatedTime: number
  passRate: number
  trainingCount: number
  lastUpdateDate: Date
  status: 'active' | 'draft' | 'archived'
  isNew: boolean
  knowledgePoints: string[]
  structure: {
    type: string
    count: number
    description: string
  }[]
  myProgress?: {
    completionRate: number
    completedCount: number
    accuracyRate: number
    lastTrainingDate?: Date
  }
}

// 推荐训练数据
const recommendedTrainings = ref<Training[]>([
  {
    id: 't1',
    title: '图形推理基础训练',
    description: '包含图形推理的基本题型和解题方法，适合初学者进行基础训练。',
    categoryId: 'graphics',
    categoryName: '图形推理',
    difficulty: 'easy',
    questionCount: 20,
    estimatedTime: 25,
    passRate: 75,
    trainingCount: 1256,
    lastUpdateDate: new Date('2024-05-20T10:00:00'),
    status: 'active',
    isNew: true,
    knowledgePoints: ['图形推理', '对称性', '数量变化', '位置变化', '组合叠加'],
    structure: [
      { type: '单选题', count: 15, description: '基础图形规律识别' },
      { type: '多选题', count: 5, description: '复杂图形组合分析' }
    ],
    myProgress: {
      completionRate: 30,
      completedCount: 6,
      accuracyRate: 67,
      lastTrainingDate: new Date('2024-05-22T14:30:00')
    }
  },
  {
    id: 't2',
    title: '逻辑判断提高训练',
    description: '针对逻辑判断的难点和易错点进行专项训练，提高解题速度和准确率。',
    categoryId: 'logic',
    categoryName: '逻辑判断',
    difficulty: 'medium',
    questionCount: 25,
    estimatedTime: 35,
    passRate: 62,
    trainingCount: 892,
    lastUpdateDate: new Date('2024-05-18T09:15:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['逻辑判断', '必然性推理', '可能性推理', '加强削弱', '前提型'],
    structure: [
      { type: '单选题', count: 20, description: '逻辑推理题目' },
      { type: '多选题', count: 5, description: '复杂逻辑分析' }
    ]
  },
  {
    id: 't3',
    title: '资料分析速算技巧',
    description: '专注于资料分析的速算技巧和解题方法，帮助提高答题效率。',
    categoryId: 'data',
    categoryName: '资料分析',
    difficulty: 'hard',
    questionCount: 15,
    estimatedTime: 25,
    passRate: 48,
    trainingCount: 635,
    lastUpdateDate: new Date('2024-05-15T11:30:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['资料分析', '增长率', '比重', '平均数', '倍数', '速算技巧'],
    structure: [
      { type: '单选题', count: 10, description: '常规计算题目' },
      { type: '填空题', count: 5, description: '精确计算题目' }
    ],
    myProgress: {
      completionRate: 100,
      completedCount: 15,
      accuracyRate: 80,
      lastTrainingDate: new Date('2024-05-20T16:45:00')
    }
  }
])

// 模拟训练数据
const trainings = ref<Training[]>([
  // 推荐训练数据已包含在上面，这里补充其他训练
  {
    id: 't4',
    title: '定义判断专项训练',
    description: '集中训练定义判断题型，掌握定义的关键信息提取和分析方法。',
    categoryId: 'definition',
    categoryName: '定义判断',
    difficulty: 'easy',
    questionCount: 15,
    estimatedTime: 20,
    passRate: 82,
    trainingCount: 1024,
    lastUpdateDate: new Date('2024-05-10T08:45:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['定义判断', '主体', '客体', '条件', '结果'],
    structure: [
      { type: '单选题', count: 15, description: '各类定义判断题目' }
    ]
  },
  {
    id: 't5',
    title: '类比推理分类训练',
    description: '按照不同的类比关系类型进行分类训练，提高类比推理能力。',
    categoryId: 'analogy',
    categoryName: '类比推理',
    difficulty: 'medium',
    questionCount: 20,
    estimatedTime: 25,
    passRate: 68,
    trainingCount: 743,
    lastUpdateDate: new Date('2024-05-05T14:00:00'),
    status: 'active',
    isNew: true,
    knowledgePoints: ['类比推理', '概念关系', '逻辑关系', '语法关系', '常识关系'],
    structure: [
      { type: '单选题', count: 15, description: '基础类比题目' },
      { type: '多选题', count: 5, description: '复杂类比题目' }
    ],
    myProgress: {
      completionRate: 50,
      completedCount: 10,
      accuracyRate: 70,
      lastTrainingDate: new Date('2024-05-21T11:20:00')
    }
  },
  {
    id: 't6',
    title: '言语理解高频成语',
    description: '针对考试中高频出现的成语进行专项训练，提高言语理解能力。',
    categoryId: 'language',
    categoryName: '言语理解',
    difficulty: 'medium',
    questionCount: 25,
    estimatedTime: 30,
    passRate: 65,
    trainingCount: 987,
    lastUpdateDate: new Date('2024-05-01T10:30:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['言语理解', '成语辨析', '语境分析', '逻辑填空'],
    structure: [
      { type: '单选题', count: 20, description: '成语辨析题目' },
      { type: '填空题', count: 5, description: '成语填空题目' }
    ]
  },
  {
    id: 't7',
    title: '数量关系经典题型',
    description: '包含数量关系中最经典的题型和解题方法，帮助建立解题思路。',
    categoryId: 'quantity',
    categoryName: '数量关系',
    difficulty: 'hard',
    questionCount: 20,
    estimatedTime: 35,
    passRate: 42,
    trainingCount: 568,
    lastUpdateDate: new Date('2024-04-28T15:15:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['数量关系', '行程问题', '工程问题', '利润问题', '排列组合', '概率问题'],
    structure: [
      { type: '单选题', count: 15, description: '常规数量关系题目' },
      { type: '填空题', count: 5, description: '计算类题目' }
    ]
  },
  {
    id: 't8',
    title: '图形推理难题突破',
    description: '针对图形推理中的难题和创新题型进行训练，突破难点。',
    categoryId: 'graphics',
    categoryName: '图形推理',
    difficulty: 'hard',
    questionCount: 15,
    estimatedTime: 30,
    passRate: 38,
    trainingCount: 429,
    lastUpdateDate: new Date('2024-04-25T09:00:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['图形推理', '空间重构', '立体图形', '创新规律'],
    structure: [
      { type: '单选题', count: 10, description: '复杂图形规律' },
      { type: '多选题', count: 5, description: '多规律综合题目' }
    ]
  },
  {
    id: 't9',
    title: '逻辑判断论证类题目',
    description: '专注于逻辑判断中的论证类题目，提高加强削弱题的解题能力。',
    categoryId: 'logic',
    categoryName: '逻辑判断',
    difficulty: 'medium',
    questionCount: 20,
    estimatedTime: 30,
    passRate: 58,
    trainingCount: 691,
    lastUpdateDate: new Date('2024-04-20T14:30:00'),
    status: 'active',
    isNew: true,
    knowledgePoints: ['逻辑判断', '加强支持', '削弱质疑', '前提假设'],
    structure: [
      { type: '单选题', count: 20, description: '论证类题目' }
    ]
  },
  {
    id: 't10',
    title: '资料分析综合训练',
    description: '综合训练资料分析各种题型，提高整体解题能力和速度。',
    categoryId: 'data',
    categoryName: '资料分析',
    difficulty: 'medium',
    questionCount: 20,
    estimatedTime: 35,
    passRate: 55,
    trainingCount: 783,
    lastUpdateDate: new Date('2024-04-15T11:45:00'),
    status: 'active',
    isNew: false,
    knowledgePoints: ['资料分析', '文字型材料', '表格型材料', '图形型材料', '综合型材料'],
    structure: [
      { type: '单选题', count: 15, description: '常规资料分析题目' },
      { type: '填空题', count: 5, description: '计算类题目' }
    ],
    myProgress: {
      completionRate: 75,
      completedCount: 15,
      accuracyRate: 73,
      lastTrainingDate: new Date('2024-05-19T15:50:00')
    }
  }
])

// 题目接口
interface Question {
  id: string
  stem: string
  type: 'single' | 'multiple' | 'blank' | 'essay'
  difficulty: 'easy' | 'medium' | 'hard'
  options?: string[]
  correctAnswers: number[] | string[]
  selectedOptions: number[]
  textAnswer: string
  explanation: string
  isCompleted: boolean
  isMarked: boolean
  imageUrl?: string
  knowledgePoints: string[]
}

// 进行中的训练
interface InProgressTraining extends Training {
  questions: Question[]
  startTime: Date
  elapsedTime: number
  remainingTime: number
}

// 完成的训练结果
interface CompletedTrainingResult extends Training {
  score: number
  totalScore: number
  accuracyRate: number
  correctCount: number
  totalCount: number
  difficultyLevel: number
  ranking: number
  beatenPercentage: number
  totalTime: number
  completionDate: Date
  typeAccuracy: {
    type: string
    accuracy: number
    correctCount: number
    totalCount: number
  }[]
  knowledgeMastery: {
    point: string
    masteryLevel: number
  }[]
  wrongQuestions: {
    id: string
    index: number
    stem: string
  }[]
  learningSuggestions: {
    id: string
    content: string
  }[]
}

// 模拟题目数据
const mockQuestions: Question[] = [
  {
    id: 'q1',
    stem: '从所给的四个选项中，选择最合适的一个填入问号处，使之呈现一定的规律性：\n图形：○ △ □ ○ △ ?',
    type: 'single',
    difficulty: 'easy',
    options: ['○', '△', '□', '◇'],
    correctAnswers: [2],
    selectedOptions: [],
    textAnswer: '',
    explanation: '观察图形序列，发现是以○ △ □为周期循环出现的，所以△后面应该是□，正确答案为C选项。',
    isCompleted: false,
    isMarked: false,
    knowledgePoints: ['图形推理', '周期性规律']
  },
  {
    id: 'q2',
    stem: '下列不属于哺乳动物特征的是：',
    type: 'single',
    difficulty: 'medium',
    options: ['胎生', '哺乳', '体温恒定', '用鳃呼吸'],
    correctAnswers: [3],
    selectedOptions: [],
    textAnswer: '',
    explanation: '哺乳动物的主要特征包括胎生、哺乳、体温恒定等，而用鳃呼吸是鱼类的特征，所以正确答案为D选项。',
    isCompleted: false,
    isMarked: false,
    knowledgePoints: ['生物学', '动物分类']
  },
  {
    id: 'q3',
    stem: '中国的首都是_________。',
    type: 'blank',
    difficulty: 'easy',
    correctAnswers: ['北京'],
    selectedOptions: [],
    textAnswer: '',
    explanation: '北京是中华人民共和国的首都，是全国的政治中心、文化中心和国际交往中心。',
    isCompleted: false,
    isMarked: false,
    knowledgePoints: ['地理', '中国国情']
  }
]

// 状态管理
const selectedTrainingDetail = ref<Training | null>(null)
const currentTraining = ref<InProgressTraining | null>(null)
const currentQuestion = computed(() => {
  return currentTraining.value?.questions[currentQuestionIndex.value] || null
})
const remainingTime = computed(() => {
  if (!currentTraining.value || !trainingOptions.timerEnabled) return 0
  return Math.max(0, currentTraining.value.remainingTime - trainingTimer.value)
})
const completedTraining = ref<CompletedTrainingResult | null>(null)

// 计算属性
const filteredTrainings = computed(() => {
  let filtered = [...trainings.value]
  
  // 根据标签筛选
  if (activeTab.value !== 'all') {
    filtered = filtered.filter(training => training.categoryId === activeTab.value)
  }
  
  // 根据难度筛选
  if (difficultyFilter.value !== 'all') {
    filtered = filtered.filter(training => training.difficulty === difficultyFilter.value)
  }
  
  // 根据关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter(training => 
      training.title.toLowerCase().includes(keyword) || 
      training.description.toLowerCase().includes(keyword) ||
      training.categoryName.toLowerCase().includes(keyword)
    )
  }
  
  // 排序
  switch (sortBy.value) {
    case 'newest':
      filtered.sort((a, b) => b.lastUpdateDate.getTime() - a.lastUpdateDate.getTime())
      break
    case 'questionsDesc':
      filtered.sort((a, b) => b.questionCount - a.questionCount)
      break
    case 'questionsAsc':
      filtered.sort((a, b) => a.questionCount - b.questionCount)
      break
    case 'passRateDesc':
      filtered.sort((a, b) => b.passRate - a.passRate)
      break
    case 'passRateAsc':
      filtered.sort((a, b) => a.passRate - b.passRate)
      break
    default:
      // 默认排序：新训练在前，然后按通过率从高到低
      filtered.sort((a, b) => {
        if (a.isNew !== b.isNew) {
          return a.isNew ? -1 : 1
        }
        return b.passRate - a.passRate
      })
  }
  
  return filtered
})

// 分页后的训练列表
const paginatedTrainings = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredTrainings.value.slice(startIndex, endIndex)
})

// 方法
const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const formatDateTime = (date: Date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const getQuestionTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    blank: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

const getDifficultyName = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficultyMap[difficulty] || difficulty
}

const getDifficultyType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

const getTrainingStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '进行中',
    draft: '草稿',
    archived: '已归档'
  }
  return statusMap[status] || status
}

const getTrainingStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: 'success',
    draft: 'info',
    archived: 'danger'
  }
  return typeMap[status] || 'info'
}

const getOptionLabel = (index: number) => {
  return String.fromCharCode(65 + index)
}

const getMasteryType = (masteryLevel: number) => {
  if (masteryLevel >= 80) return 'success'
  if (masteryLevel >= 60) return 'warning'
  return 'danger'
}

const formatPassRate = (_percentage: number) => {
  return ''
}

const formatTrainingProgress = (_percentage: number) => {
  return ''
}

const formatProgressPercentage = (percentage: number) => {
  return `${percentage}%`
}

const getUserAnswerDisplay = () => {
  if (!currentQuestion.value) return ''
  
  if (currentQuestion.value.type === 'blank' || currentQuestion.value.type === 'essay') {
    return currentQuestion.value.textAnswer || '未作答'
  } else if (currentQuestion.value.options) {
    if (currentQuestion.value.selectedOptions.length === 0) {
      return '未作答'
    }
    if (!currentQuestion.value) return ''
    
    return currentQuestion.value.selectedOptions
      .map((answer: number) => {
        if (currentQuestion.value && currentQuestion.value.options) {
          return getOptionLabel(answer) + '.' + currentQuestion.value.options[answer]
        }
        return getOptionLabel(answer)
      })
      .join('，')
  }
  return ''
}

const getCorrectAnswerDisplay = () => {
  if (!currentQuestion.value) return ''
  
  if (currentQuestion.value.type === 'blank' || currentQuestion.value.type === 'essay') {
    return currentQuestion.value.correctAnswers.join('、')
  } else if (currentQuestion.value && currentQuestion.value.options) {
    return currentQuestion.value.correctAnswers
      .map(answer => {
        if (typeof answer === 'number' && currentQuestion.value && currentQuestion.value.options) {
          return getOptionLabel(answer) + '.' + currentQuestion.value.options[answer]
        }
        return answer
      })
      .join('，')
  }
  return ''
}

// 标签点击处理
const handleTabClick = () => {
  currentPage.value = 1
}

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1
}

// 刷新训练列表
const refreshTrainingList = () => {
  isLoading.value = true
  // 模拟刷新操作
  setTimeout(() => {
    isLoading.value = false
    ElMessage.success('训练列表已刷新')
  }, 500)
}

// 查看训练历史
const viewTrainingHistory = () => {
  ElMessage.info('查看训练历史功能待实现')
}

// 查看训练详情
const viewTrainingDetails = (id: string) => {
  const training = trainings.value.find(t => t.id === id) || recommendedTrainings.value.find(t => t.id === id)
  if (training) {
    selectedTrainingDetail.value = training
    trainingDetailDialogVisible.value = true
  }
}

// 开始训练
const startTraining = (id: string) => {
  const training = trainings.value.find(t => t.id === id) || recommendedTrainings.value.find(t => t.id === id)
  if (training) {
    selectedTrainingDetail.value = training
    startTrainingDialogVisible.value = true
  }
}

// 确认开始训练
const confirmStartTraining = () => {
  if (!selectedTrainingDetail.value) return
  
  isStartingTraining.value = true
  
  // 模拟加载题目延迟
  setTimeout(() => {
    // 创建进行中的训练
    const trainingDetail = selectedTrainingDetail.value
    const inProgressTraining: InProgressTraining = {
      id: trainingDetail?.id || `training_${Date.now()}`,
      title: trainingDetail?.title || '新训练',
      description: trainingDetail?.description || '',
      categoryId: trainingDetail?.categoryId || '',
      categoryName: trainingDetail?.categoryName || '默认分类',
      difficulty: trainingDetail?.difficulty || 'medium',
      questionCount: trainingDetail?.questionCount || 0,
      estimatedTime: trainingDetail?.estimatedTime || 0,
      passRate: trainingDetail?.passRate || 0,
      trainingCount: trainingDetail?.trainingCount || 0,
      lastUpdateDate: trainingDetail?.lastUpdateDate || new Date(),
      status: trainingDetail?.status || 'draft',
      isNew: trainingDetail?.isNew || false,
      knowledgePoints: trainingDetail?.knowledgePoints || [],
      structure: trainingDetail?.structure || [],
      questions: generateMockQuestions(trainingDetail as Training),
      startTime: new Date(),
      elapsedTime: 0,
      remainingTime: (trainingDetail?.estimatedTime || 0) * 60
    }
    
    currentTraining.value = inProgressTraining
    currentQuestionIndex.value = 0
    textAnswer.value = ''
    trainingTimer.value = 0
    
    // 关闭开始对话框，打开训练对话框
    startTrainingDialogVisible.value = false
    trainingInProgressDialogVisible.value = true
    isStartingTraining.value = false
    
    // 开始计时
    startTimer()
  }, 1000)
}

// 生成模拟题目
const generateMockQuestions = (_training: Training): Question[] => {
  // 这里应该根据训练配置生成题目，这里简化处理
  // 复制模拟题目数据并重置状态
  return mockQuestions.map(q => ({
    ...q,
    selectedOptions: [],
    textAnswer: '',
    isCompleted: false,
    isMarked: false
  }))
}

// 开始计时
const startTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
  
  timerInterval.value = window.setInterval(() => {
    trainingTimer.value++
    
    // 检查是否超时
    if (trainingOptions.timerEnabled && remainingTime.value <= 0) {
      handleTrainingTimeout()
    }
  }, 1000)
}

// 停止计时
const stopTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
    timerInterval.value = null
  }
}

// 处理训练超时
const handleTrainingTimeout = () => {
  ElMessage.warning('训练时间已结束，自动提交')
  
  // 标记所有未完成的题目为未作答
  currentTraining.value?.questions.forEach(question => {
    if (!question.isCompleted) {
      question.isCompleted = true
    }
  })
  
  // 提交训练结果
  submitTrainingResult()
}

// 选择选项
const selectOption = (index: number) => {
  if (!currentQuestion.value || currentQuestion.value.isCompleted) return
  
  if (currentQuestion.value.type === 'single') {
    // 单选题只能选择一个选项
    currentQuestion.value.selectedOptions = [index]
  } else if (currentQuestion.value.type === 'multiple') {
    // 多选题可以选择多个选项
    const optionIndex = currentQuestion.value.selectedOptions.indexOf(index)
    if (optionIndex > -1) {
      currentQuestion.value.selectedOptions.splice(optionIndex, 1)
    } else {
      currentQuestion.value.selectedOptions.push(index)
    }
  }
}

// 切换标记题目
const toggleMarkQuestion = () => {
  if (currentQuestion.value) {
    currentQuestion.value.isMarked = !currentQuestion.value.isMarked
  }
}

// 跳转到指定题目
const jumpToQuestion = (index: number) => {
  if (index !== currentQuestionIndex.value) {
    currentQuestionIndex.value = index
    textAnswer.value = currentQuestion.value?.textAnswer || ''
  }
}

// 上一题
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    textAnswer.value = currentQuestion.value?.textAnswer || ''
  }
}

// 下一题
const nextQuestion = () => {
  if (currentTraining.value && currentQuestionIndex.value < currentTraining.value.questions.length - 1) {
    currentQuestionIndex.value++
    textAnswer.value = currentQuestion.value?.textAnswer || ''
  } else {
    // 最后一题，提交答案后显示结果
    if (currentQuestion.value && !currentQuestion.value.isCompleted) {
      submitAnswer()
    } else {
      submitTrainingResult()
    }
  }
}

// 提交答案
const submitAnswer = () => {
  if (!currentQuestion.value || currentQuestion.value.isCompleted) return
  
  isSubmittingAnswer.value = true
  
  // 保存文本答案
  if (currentQuestion.value.type === 'blank' || currentQuestion.value.type === 'essay') {
    currentQuestion.value.textAnswer = textAnswer.value
  }
  
  // 模拟提交延迟
  setTimeout(() => {
    currentQuestion.value!.isCompleted = true
    isSubmittingAnswer.value = false
  }, 500)
}

// 提交训练结果
const submitTrainingResult = () => {
  if (!currentTraining.value) return
  
  // 停止计时
  stopTimer()
  
  // 计算训练结果
  const correctCount = currentTraining.value.questions.filter(q => {
    if (q.type === 'blank' || q.type === 'essay') {
      // 简单的文本答案比较
      return q.correctAnswers.some(answer => 
        q.textAnswer.toLowerCase().includes((answer as string).toLowerCase())
      )
    } else {
      // 选项答案比较
      return q.selectedOptions.length === q.correctAnswers.length &&
        q.selectedOptions.every(option => (q.correctAnswers as number[]).includes(option))
    }
  }).length
  
  const totalCount = currentTraining.value.questions.length
  const accuracyRate = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0
  const score = Math.round((accuracyRate / 100) * 100) // 满分100分
  
  // 创建完成的训练结果
  const result: CompletedTrainingResult = {
    ...currentTraining.value,
    score,
    totalScore: 100,
    accuracyRate,
    correctCount,
    totalCount,
    difficultyLevel: 3.5, // 模拟难度系数
    ranking: 25, // 模拟排名百分比
    beatenPercentage: 75, // 击败的用户百分比
    totalTime: trainingTimer.value,
    completionDate: new Date(),
    typeAccuracy: [
      { type: 'single', accuracy: 80, correctCount: 4, totalCount: 5 },
      { type: 'multiple', accuracy: 60, correctCount: 3, totalCount: 5 },
      { type: 'blank', accuracy: 70, correctCount: 7, totalCount: 10 }
    ],
    knowledgeMastery: [
      { point: '图形推理', masteryLevel: 85 },
      { point: '定义判断', masteryLevel: 70 },
      { point: '类比推理', masteryLevel: 60 },
      { point: '逻辑判断', masteryLevel: 75 },
      { point: '言语理解', masteryLevel: 80 }
    ],
    wrongQuestions: currentTraining.value.questions
      .filter((q) => {
        // 简单判断是否错误
        if (q.type === 'blank' || q.type === 'essay') {
          return !q.correctAnswers.some(answer => 
            q.textAnswer.toLowerCase().includes((answer as string).toLowerCase())
          )
        } else {
          return q.selectedOptions.length !== q.correctAnswers.length ||
            !q.selectedOptions.every(option => (q.correctAnswers as number[]).includes(option))
        }
      })
      .map((q) => ({
        id: q.id,
        index: currentTraining.value!.questions.findIndex(item => item.id === q.id),
        stem: q.stem
      })),
    learningSuggestions: [
      { id: 's1', content: '加强图形推理中位置类题目的练习，提高空间想象能力' },
      { id: 's2', content: '注意定义判断中主体和客体的分析，避免遗漏关键信息' },
      { id: 's3', content: '类比推理需要积累更多的常识知识，扩大知识面' }
    ]
  }
  
  completedTraining.value = result
  
  // 关闭训练对话框，打开结果对话框
  trainingInProgressDialogVisible.value = false
  trainingResultDialogVisible.value = true
}

// 切换训练全屏
const toggleTrainingFullscreen = () => {
  isTrainingFullscreen.value = !isTrainingFullscreen.value
}

// 处理训练对话框关闭
const handleTrainingDialogClose = () => {
  if (trainingTimer.value > 0) {
    ElMessageBox.confirm(
      '确定要结束当前训练吗？已完成的进度将被保存。',
      '确认结束',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续训练',
        type: 'warning'
      }
    ).then(() => {
      stopTimer()
      trainingInProgressDialogVisible.value = false
    }).catch(() => {
      // 用户选择继续训练
    })
  } else {
    trainingInProgressDialogVisible.value = false
  }
}

// 处理结果对话框关闭
const handleResultDialogClose = () => {
  trainingResultDialogVisible.value = false
}

// 复习错题
const reviewWrongQuestion = (_id: string) => {
  ElMessage.info('复习错题功能待实现')
}

// 保存训练结果
const saveTrainingResult = () => {
  ElMessage.success('训练结果已保存')
}

// 分享训练结果
const shareTrainingResult = () => {
  ElMessage.info('分享功能待实现')
}

// 查看全部题目
const reviewAllQuestions = () => {
  ElMessage.info('查看全部题目功能待实现')
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 组件挂载时初始化
onMounted(() => {
  // 可以在这里加载用户的训练数据
})

// 组件卸载时清理
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.special-training-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.category-navigation {
  margin-bottom: 30px;
}

.category-card {
  border-radius: 12px;
  overflow: hidden;
}

.category-tabs {
  width: 100%;
}

.recommended-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.recommended-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.recommended-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
}

.recommended-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.recommended-card-content {
  padding: 20px;
}

.recommended-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.recommended-card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
  margin-right: 10px;
}

.recommended-card-badge {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.badge-easy {
  background-color: #10b981;
}

.badge-medium {
  background-color: #f59e0b;
}

.badge-hard {
  background-color: #ef4444;
}

.recommended-card-info {
  margin-bottom: 15px;
}

.recommended-card-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #6b7280;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.recommended-card-desc {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.6;
}

.recommended-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommended-card-category {
  font-size: 14px;
  color: #6b7280;
}

.trainings-list-section {
  margin-bottom: 30px;
}

.trainings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.trainings-filter {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.filter-select {
  width: 120px;
}

.trainings-card {
  border-radius: 12px;
  overflow: hidden;
}

.trainings-content {
  padding: 20px;
}

.no-trainings {
  text-align: center;
  padding: 60px 20px;
}

.no-trainings-text {
  margin-top: 10px;
  font-size: 16px;
  color: #6b7280;
}

.training-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  flex: 1;
}

.new-tag {
  margin-left: auto;
}

.pass-rate-text {
  margin-left: 10px;
  font-size: 14px;
  color: #6b7280;
}

.trainings-pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 训练详情对话框样式 */
.training-detail-content {
  padding: 10px 0;
}

.training-detail-header {
  margin-bottom: 20px;
}

.training-detail-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.training-detail-badges {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.training-detail-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.training-detail-description,
.training-detail-knowledge,
.training-detail-structure,
.training-detail-progress {
  margin-bottom: 30px;
}

.training-detail-description h4,
.training-detail-knowledge h4,
.training-detail-structure h4,
.training-detail-progress h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 15px;
}

.training-detail-description p {
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
}

.knowledge-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.knowledge-tag {
  background-color: #e5e7eb;
  color: #374151;
  font-size: 14px;
}

.progress-info {
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #6b7280;
}

.training-detail-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 开始训练对话框样式 */
.start-training-content {
  padding: 10px 0;
}

.start-training-header {
  margin-bottom: 20px;
}

.start-training-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.start-training-desc {
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
}

.start-training-notice {
  background-color: #fef3c7;
  border: 1px solid #fbbf24;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.notice-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #92400e;
}

.notice-item:last-child {
  margin-bottom: 0;
}

.start-training-options {
  margin-bottom: 10px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
}

.option-item:last-child {
  margin-bottom: 0;
}

.start-training-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 训练进行中对话框样式 */
.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.progress-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.progress-stats {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #6b7280;
}

.progress-remaining {
  font-weight: 500;
}

.time-warning {
  color: #f59e0b;
}

.time-danger {
  color: #ef4444;
}

.question-navigation {
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.navigation-label {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.navigation-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.navigation-item {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  background-color: #e5e7eb;
  color: #6b7280;
}

.navigation-item:hover {
  background-color: #d1d5db;
}

.navigation-item.current {
  background-color: #3b82f6;
  color: white;
}

.navigation-item.completed {
  background-color: #10b981;
  color: white;
}

.navigation-item.marked {
  border: 2px solid #f59e0b;
}

.marked-indicator {
  position: absolute;
  top: -5px;
  right: -5px;
  font-size: 12px;
}

.question-content {
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.question-type {
  padding: 6px 12px;
  background-color: #3b82f6;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.question-difficulty {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.difficulty-easy {
  background-color: #10b981;
}

.difficulty-medium {
  background-color: #f59e0b;
}

.difficulty-hard {
  background-color: #ef4444;
}

.marked-button {
  color: #f59e0b;
}

.question-stem {
  margin-bottom: 20px;
}

.question-stem h4 {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-image {
  text-align: center;
  margin-bottom: 20px;
}

.question-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.option-item {
  padding: 15px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.option-item:hover:not(.disabled) {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.option-item.selected {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.option-item.disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.option-label {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #e5e7eb;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
  flex-shrink: 0;
}

.option-item.selected .option-label {
  background-color: #3b82f6;
  color: white;
}

.option-content {
  flex: 1;
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
}

.question-answer-input {
  margin-bottom: 20px;
}

.answer-explanation {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.user-answer,
.correct-answer,
.explanation {
  margin-bottom: 15px;
}

.user-answer h4,
.correct-answer h4,
.explanation h4 {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.user-answer p,
.correct-answer p,
.explanation p {
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
}

.training-dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.training-navigation-buttons {
  display: flex;
  gap: 10px;
}

/* 训练结果对话框样式 */
.result-overview {
  margin-bottom: 30px;
}

.result-header {
  margin-bottom: 20px;
}

.result-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.result-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #6b7280;
  flex-wrap: wrap;
}

.result-stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.result-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.result-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.result-card-content {
  text-align: center;
  padding: 20px;
}

.result-card-title {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 10px;
}

.result-card-value {
  font-size: 32px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 5px;
}

.result-card-subtitle {
  font-size: 12px;
  color: #9ca3af;
}

.score-card {
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
}

.score-card .result-card-title,
.score-card .result-card-value,
.score-card .result-card-subtitle {
  color: white;
}

.accuracy-card {
  background: linear-gradient(135deg, #10b981, #059669);
}

.accuracy-card .result-card-title,
.accuracy-card .result-card-value,
.accuracy-card .result-card-subtitle {
  color: white;
}

.difficulty-card {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.difficulty-card .result-card-title,
.difficulty-card .result-card-value,
.difficulty-card .result-card-subtitle {
  color: white;
}

.rank-card {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.rank-card .result-card-title,
.rank-card .result-card-value,
.rank-card .result-card-subtitle {
  color: white;
}

.answer-analysis {
  margin-bottom: 10px;
}

.answer-analysis h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
}

.analysis-section {
  margin-bottom: 25px;
}

.analysis-section h5 {
  font-size: 14px;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 15px;
}

.type-accuracy {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.type-accuracy-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.type-name {
  width: 100px;
  font-size: 14px;
  color: #6b7280;
}

.type-stats {
  font-size: 14px;
  color: #6b7280;
  min-width: 80px;
}

.knowledge-mastery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.mastery-tag {
  font-size: 14px;
}

.no-wrong-questions {
  text-align: center;
  padding: 40px 20px;
}

.no-wrong-questions-text {
  margin-top: 10px;
  font-size: 16px;
  color: #6b7280;
}

.wrong-questions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.wrong-question-item {
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #fef2f2;
}

.wrong-question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.wrong-question-index {
  font-size: 14px;
  font-weight: 600;
  color: #dc2626;
}

.wrong-question-stem {
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
}

.learning-suggestions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 15px;
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #0369a1;
}

.result-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .special-training-view {
    padding: 10px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-select {
    flex: 1;
    min-width: 120px;
  }
  
  .result-stats-cards {
    grid-template-columns: 1fr;
  }
  
  .training-dialog-footer {
    flex-direction: column;
    gap: 10px;
  }
  
  .training-navigation-buttons {
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .recommended-grid {
    grid-template-columns: 1fr;
  }
  
  .training-detail-stats {
    flex-direction: column;
    gap: 10px;
  }
  
  .progress-stats {
    flex-direction: column;
    gap: 5px;
  }
  
  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>